package sgc.beans;

import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import sgc.struc.MaterialPrice;

@ManagedBean(name = "materialPriceBean")
@RequestScoped
public class MaterialPriceBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private MaterialPrice price;
	private DataSource ds;
	private HtmlDataTable htmlDataTable;

	public MaterialPriceBean() {
		try {
			Context ctx = new InitialContext();
			ds = (DataSource) ctx.lookup("java:comp/env/jdbc/sgcweb");
		} catch (NamingException e) {
			e.printStackTrace();
		}
		price = new MaterialPrice();
	}

	public MaterialPrice getPrice() {
		return price;
	}

	public void setPrice(MaterialPrice price) {
		this.price = price;
	}

	public HtmlDataTable getHtmlDataTable() {
		return htmlDataTable;
	}

	public void setHtmlDataTable(HtmlDataTable htmlDataTable) {
		this.htmlDataTable = htmlDataTable;
	}

	private java.sql.Date convertDate(java.util.Date jDate) {
		java.sql.Date sqlDate;
		long t;

		if (jDate == null) {
			sqlDate = new java.sql.Date(0);
		} else {
			t = jDate.getTime();
			sqlDate = new java.sql.Date(t);
		}
		return sqlDate;
	}

	private int parseInt(String campo) {
		if (campo == null) {
			return 0;
		} else {
			String delims = " - ";
			String[] tokens = campo.split(delims);
			return Integer.parseInt(tokens[0]);
		}
	}

	public void materialChange(ValueChangeEvent e) {

	}

	public List<MaterialPrice> getMaterialList() throws SQLException {

		if (ds == null)
			throw new SQLException("Can't get data source");
		Connection con = ds.getConnection();
		if (con == null)
			throw new SQLException("Can't get database connection");

		String simpleProc = "{ CALL sp_getAllMaterialPrice_2(?, ?) }";
		CallableStatement cs = con.prepareCall(simpleProc);
		cs.setInt(1, act_company());
		cs.setInt(2, parseInt(price.getMat_name()));

		cs.execute();
		ResultSet result = cs.getResultSet();

		List<MaterialPrice> list = new ArrayList<MaterialPrice>();

		while (result.next()) {
			if (result.getInt(1) != 0) {
				MaterialPrice aux_price = new MaterialPrice();
				aux_price.setMat_code(result.getInt(1));
				aux_price.setMat_name(result.getString(2));
				aux_price.setCompany_name(result.getString(3));
				aux_price.setCompany_code(result.getInt(4));
				aux_price.setPrice(result.getDouble(5));
				aux_price.setValid_from(result.getDate(6));
				list.add(aux_price);
			}
		}
		con.close();

		return list;
	}

	private int act_company() {
		int company;
		company = 0;
		try {
			FacesContext context = FacesContext.getCurrentInstance();
			CheckUserBean cu = (CheckUserBean) context.getApplication()
					.evaluateExpressionGet(context, "#{checkUserBean}",
							CheckUserBean.class);
			company = cu.getUsuario().getCompany_code();
		} catch (Exception e) {
		}
		return company;
	}

	public void edit() {
		MaterialPrice aux_price = (MaterialPrice) htmlDataTable.getRowData();
		
		price.setCode(aux_price.getCode());
		price.setCompany_code(aux_price.getCompany_code());
		price.setCompany_name(aux_price.getCompany_name());
		price.setMat_code(aux_price.getMat_code());
		price.setMat_name( aux_price.getMat_code() + " - " + aux_price.getMat_name());
		price.setPrice(aux_price.getPrice());
		price.setValid_from(aux_price.getValid_from());
		
	}

	public boolean check(int p_company, int p_mat, Date p_valid)
			throws SQLException {
		int aux_cod;
		if (ds == null)
			throw new SQLException("Can't get data source");
		Connection con = ds.getConnection();
		if (con == null)
			throw new SQLException("Can't get database connection");

		String simpleProc = "{ CALL sp_GetMaterialPrice(?, ?, ?) }";
		CallableStatement cs = con.prepareCall(simpleProc);
		cs.setInt(1, p_company);
		cs.setInt(2, p_mat);
		cs.setDate(3, convertDate(p_valid));
		cs.execute();
		ResultSet result = cs.getResultSet();
		result.next();
		aux_cod = result.getInt(1);
		con.close();

		if (aux_cod != 0) {
			return true;
		} else {
			return false;
		}
	}

	public void save() throws SQLException {
		if (ds == null)
			throw new SQLException("Can't get data source");
		Connection con = ds.getConnection();
		if (con == null)
			throw new SQLException("Can't get database connection");

		String simpleProc;
		if (check(act_company(), parseInt(price.getMat_name()), price.getValid_from()) == true) {
			simpleProc = "{ CALL sp_updMaterialPrice(?,?,?,?) }";
		} else {
			simpleProc = "{ CALL sp_addMaterialPrice(?,?,?,?) }";
		}
		price.setCompany_code(act_company());
		CallableStatement cs = con.prepareCall(simpleProc);
		cs.setInt(1, act_company());
		cs.setInt(2, parseInt(price.getMat_name()));
		cs.setDouble(3, price.getPrice());
		cs.setDate(4, convertDate(price.getValid_from()));

		cs.execute();
		ResultSet result = cs.getResultSet();
		result.next();
		String aux_message = result.getString(3);
		FacesContext.getCurrentInstance()
				.addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_INFO,
								aux_message, null));
//		price = null;
		price.setPrice(0);
		price.setValid_from(null);
		
	}
}
